package data.nanjing.expo.filter;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.FilterConfig;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import data.nanjing.expo.models.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

@WebFilter(filterName="authFilter", urlPatterns={"/*"})
@Component
public class AuthFilter implements Filter{

    @Value("${auth.openUrl}")
    private String openUrl;

    @Override
    public void init(FilterConfig args) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        HttpSession session = req.getSession();
        //添加模拟用户
        /*User user1 = new User();
        user1.setId(1);
        user1.setUserName("admin");
        user1.setPhoneNo("13088888888");
        user1.setUserQq("12345678");
        if(session.getAttribute("user") == null){
            session.setAttribute("user", user1);
        }*/
        String url = req.getRequestURI();
        User user = (User) session.getAttribute("user");
        if (url.startsWith("/api") && !url.startsWith("/api/common")) {
            if (user == null) {
                res.sendRedirect("/api/common/nosign");
            }else {
                filterChain.doFilter(request, response);
            }
        }else {
            filterChain.doFilter(request, response);
        }
        //res.sendRedirect("/login");
    }

    @Override
    public void destroy() {

    }

    public String[] getOpenUrl() {
        if(this.openUrl == null || this.openUrl.isEmpty()) {
            return null;
        }else{
            return this.openUrl.split(";");
        }
    }
}

